<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2020/11/27
 * Time: 22:23
 * @link http://www.lmterp.cn
 */

namespace app\admin\controller\system;

use app\admin\controller\BaseController;
use app\common\model\JobFlowModule;
use app\common\model\JobFlowSettings;

/**
 * 配置审批工作流
 * Class JobFlowController
 * @package app\admin\controller\system
 */
class JobsController extends BaseController
{
    /**
     * 工作流首页
     * @date 2020/11/27
     * @author longli
     */
    public function index()
    {
        if($this->request->isAjax())
        {
            $settings = JobFlowSettings::with(['flow'])->order('flow_id, node');
            $this->searchModel($settings, [
                'eq' => ['flow_id'],
            ]);
            $settings = $settings->select();
            $ids = [];
            foreach($settings as $s) $ids = array_merge($ids, explode(',', $s->user_id));
            $users = \app\common\model\Admin::getNicknameByIds(array_unique($ids));
            foreach($settings as $s)
            {
                $nickname = [];
                foreach(explode(',', $s->user_id) as $i) if(isset($users[$i]))$nickname[] = $users[$i];
                $s['nickname'] = join(', ', $nickname);
            }
            $this->assign('list', $settings);
            return $this->fetch('lists');
        }
        $this->assign('module', \app\common\model\JobFlowModule::getAll());
        return $this->fetch('index');
    }

    /**
     * 添加审批工作流
     * @date 2020/11/27
     * @author longli
     */
    public function add()
    {
        if($flowId = $this->request->get('flow_id'))
            $this->assign('flow', JobFlowModule::get($flowId));
        $this->assign('module', \app\common\model\JobFlowModule::getAll());
        return $this->fetch('add');
    }

    /**
     * 保存审批工作流
     * @date 2020/11/27
     * @author longli
     */
    public function save()
    {
        $validate = \think\facade\Validate::make([
            'flow_id'  => 'require',
            'name'  => 'require|array',
            'user_id'  => 'require|array',
        ],[
            'flow_id.require' => '配置模块',
            'name.require' => '审批组必填',
            'name.array' => '审批组必须是数组',
            'user_id.require' => '审批人必填',
            'user_id.array' => '审批人必须是数组',
        ]);
        $post = $this->request->post();
        if(!$validate->batch()->check($post))$this->error(join(', ', $validate->getError()));
        if(!isset($post['old_flow_id']) && JobFlowSettings::where(['flow_id' => $post['flow_id']])->count())
            $this->error("模块已配置过，请勿重复配置");
        $dataList = [];
        $last = count($post['name']);
        foreach($post['name'] as $k => $n)
        {
            $n = trim($n);
            if(empty($n)) $this->error("审批组名称不能为空");
            if(empty($post['user_id'][$k])) $this->error("审批人不能为空");
            $node = $k + 1;
            $dataList[] = [
                'name' => $n,
                'user_id' => $post['user_id'][$k],
                'node' => $node,
                'is_end' => $last == $node ? 1 : 0,
                'flow_id' => $post['flow_id'],
                'remark' => isset($post['remark']) ? $post['remark'][$k] : '',
            ];
        }
        try
        {
            \think\Db::startTrans();
            if(isset($post['old_flow_id'])) JobFlowSettings::where(['flow_id' => $post['old_flow_id']])->delete();
            foreach($dataList as $data)
                \app\common\service\system\JobFlowService::getInstance()->addSettings($data);
            \think\Db::commit();
            $this->success('保存成功');
        }catch (\think\Exception\DbException $exception)
        {
            \think\Db::rollback();
            $this->error('保存失败');
        }
    }
}